module  WRBACK  (
        //      Inputs
        mem_wb,
        addr_in,
        mem_pl,
        lbi_pl,
        inst,
        clk,
        rst,
        //      Outputs
        reg_wr,
        reg_wr_data,
        reg_wr_addr,
        err     );

        input   [3:0]   mem_wb;
        input   [15:0]  addr_in;
        input   [15:0]  mem_pl;
        input   [15:0]  lbi_pl;
        input   [8:0]   inst;
        input           clk;
        input           rst;

        output          reg_wr;
        output  [15:0]  reg_wr_data;
        output  [2:0]   reg_wr_addr;
        output          err;
        
        wire            memtoreg;
        wire    [1:0]   regdst;
        assign          memtoreg = mem_wb[3];
        assign          reg_wr = mem_wb[2];
        assign          regdst = mem_wb[1:0];

        assign  reg_wr_addr =   
                (regdst==2'b00)?inst[2:0]
                :   (regdst==2'b01)?inst[8:6]
                :   ((regdst==2'b10)?inst[5:3]:3'b111);

        assign  reg_wr_data = (&regdst) ? addr_in 
                        : memtoreg ? mem_pl : lbi_pl ;

endmodule
